<script setup lang="ts">
import type { IMetaWarehouse } from '@/api/interface/rescue/meta/metaWarehouse'

import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import {
  createMetaWarehouseApi,
  deleteMetaWarehouseApi,
  getMetaWarehouseListApi,
  updateMetaWarehouseApi,
} from '@/api/modules/rescue/meta/metaWarehouse'
import WarehouseFilter from '@/components/rescue/filter/warehouse-filter.vue'
import WarehouseCard from '@/components/rescue/meta/warehouse/WarehouseCard.vue'
import WarehouseDetail from '@/components/rescue/meta/warehouse/WarehouseDetail.vue'
import WarehouseForm from '@/components/rescue/meta/warehouse/WarehouseForm.vue'
import { showToast } from '@/utils/toast'

// 筛选参数（直接用于WarehouseFilter组件）
const filterParams = ref({
  name: '',
  address: '',
  enable: null as boolean | null,
  common: null as boolean | null,
  page: 1,
  limit: 10,
})

const warehouseList = ref<IMetaWarehouse.Row[]>([])
const selectedIds = ref<number[]>([])
const currentPage = ref(1)
const totalPages = ref(1)
const total = ref(0)
const loading = ref(false)

// 弹窗控制
const detailVisible = ref(false)
const formVisible = ref(false)
const currentWarehouse = ref<IMetaWarehouse.Row | null>(null)

// 清理undefined参数并处理boolean值
function cleanParams(params: any) {
  const cleaned: any = {}
  Object.keys(params).forEach((key) => {
    const value = params[key]

    // 跳过undefined、null和空字符串
    if (value === undefined || value === null || value === '') {
      return
    }

    // enable和common字段已经是boolean类型，直接使用
    cleaned[key] = value
  })

  console.log('清理后的参数:', cleaned) // 调试日志
  return cleaned
}

// 获取仓库列表
async function fetchWarehouseList() {
  loading.value = true
  try {
    const params = cleanParams({
      ...filterParams.value,
      page: currentPage.value,
    })
    console.log('搜索参数:', params) // 调试日志
    console.log('原始筛选参数:', filterParams.value) // 调试日志
    const response = await getMetaWarehouseListApi(params)
    warehouseList.value = response.data.rows
    total.value = response.data.total
    totalPages.value = Math.ceil(response.data.total / filterParams.value.limit)
  } catch (error) {
    showToast('获取仓库列表失败')
    console.error('获取仓库列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听筛选参数变化
watch(
  filterParams,
  (newVal) => {
    console.log('筛选参数变化:', newVal) // 调试日志
    console.log('筛选参数类型检查:', {
      name: typeof newVal.name,
      address: typeof newVal.address,
      enable: typeof newVal.enable,
      common: typeof newVal.common,
    })
    console.log('筛选参数值检查:', {
      name: newVal.name,
      address: newVal.address,
      enable: newVal.enable,
      common: newVal.common,
    })
  },
  { deep: true },
)

// 搜索处理
function handleSearch() {
  console.log('触发搜索，当前筛选条件:', filterParams.value) // 调试日志
  console.log('筛选条件详情:', {
    name: filterParams.value.name,
    address: filterParams.value.address,
    enable: filterParams.value.enable,
    common: filterParams.value.common,
  })
  console.log('筛选条件类型:', {
    name: typeof filterParams.value.name,
    address: typeof filterParams.value.address,
    enable: typeof filterParams.value.enable,
    common: typeof filterParams.value.common,
  })
  // 确保分页重置
  currentPage.value = 1
  // 延迟一点执行，确保参数同步完成
  nextTick(() => {
    fetchWarehouseList()
  })
}

// 重置搜索
function handleReset() {
  console.log('触发重置') // 调试日志
  // 重置筛选参数
  filterParams.value = {
    name: '',
    address: '',
    enable: null,
    common: null,
    page: 1,
    limit: 10,
  }
  // 重置分页
  currentPage.value = 1
  // 重新获取数据
  nextTick(() => {
    fetchWarehouseList()
  })
}

// 分页处理
function handlePageChange(page: number) {
  currentPage.value = page
  fetchWarehouseList()
}

// 选择处理
function handleSelect(id: number, checked: boolean) {
  if (checked) {
    selectedIds.value.push(id)
  } else {
    const index = selectedIds.value.indexOf(id)
    if (index > -1) {
      selectedIds.value.splice(index, 1)
    }
  }
}

// 卡片点击
function handleCardClick(warehouse: IMetaWarehouse.Row) {
  currentWarehouse.value = warehouse
  detailVisible.value = true
}

// 新增仓库
function handleAdd() {
  currentWarehouse.value = null
  formVisible.value = true
}

// 编辑仓库
function handleEdit(warehouse: IMetaWarehouse.Row) {
  currentWarehouse.value = warehouse
  formVisible.value = true
}

// 删除仓库
async function handleDelete(warehouse: IMetaWarehouse.Row) {
  try {
    await deleteMetaWarehouseApi({ ids: [warehouse.id] })
    showToast('删除成功')
    fetchWarehouseList()
  } catch (error) {
    showToast('删除失败')
    console.error('删除失败:', error)
  }
}

// 批量删除
async function handleBatchDelete() {
  if (selectedIds.value.length === 0) {
    showToast('请选择要删除的仓库')
    return
  }

  try {
    await deleteMetaWarehouseApi({ ids: selectedIds.value })
    showToast('批量删除成功')
    selectedIds.value = []
    fetchWarehouseList()
  } catch (error) {
    showToast('批量删除失败')
    console.error('批量删除失败:', error)
  }
}

// 表单提交处理
async function handleFormSubmit(formData: IMetaWarehouse.CreateForm | IMetaWarehouse.UpdateForm) {
  try {
    if (currentWarehouse.value) {
      // 更新
      await updateMetaWarehouseApi(formData as IMetaWarehouse.UpdateForm)
    } else {
      // 新增
      await createMetaWarehouseApi(formData as IMetaWarehouse.CreateForm)
    }

    showToast(currentWarehouse.value ? '更新成功' : '新增成功')
    formVisible.value = false
    fetchWarehouseList()
  } catch (error) {
    showToast(currentWarehouse.value ? '更新失败' : '新增失败')
    console.error('表单提交失败:', error)
  }
}

// 页面加载
onMounted(() => {
  fetchWarehouseList()
})
</script>

<template>
  <view class="warehouse-page">
    <!-- 筛选区域 -->
    <WarehouseFilter
      v-model="filterParams"
      :default-expanded="false"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 操作按钮 -->
    <view class="action-section">
      <wd-button class="action-btn add-btn" @click="handleAdd">
        <wd-icon name="plus" size="16px" />
        <text>新增仓库</text>
      </wd-button>
      <wd-button
        class="action-btn delete-btn"
        :class="{ disabled: selectedIds.length === 0 }"
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete"
      >
        <wd-icon name="delete" size="16px" />
        <text>批量删除</text>
      </wd-button>
    </view>

    <!-- 仓库卡片列表 -->
    <view class="warehouse-list">
      <WarehouseCard
        v-for="item in warehouseList"
        :key="item.id"
        :warehouse="item"
        :selected="selectedIds.includes(item.id)"
        :show-checkbox="true"
        @card-click="handleCardClick"
        @select-change="(checked) => handleSelect(item.id, checked)"
        @view-detail="handleCardClick"
        @edit="handleEdit"
        @delete="handleDelete"
      />
    </view>

    <!-- 分页 -->
    <view class="pagination-section">
      <wd-pagination
        v-model="currentPage"
        :total="total"
        :page-size="filterParams.limit"
        @change="handlePageChange"
      />
    </view>

    <!-- 详情弹窗 -->
    <wd-popup
      v-model="detailVisible"
      position="bottom"
      :safe-area-inset-bottom="true"
      class="warehouse-detail-popup"
      @close="detailVisible = false"
    >
      <view class="popup-container">
        <WarehouseDetail
          v-if="detailVisible"
          :warehouse="currentWarehouse"
          @close="detailVisible = false"
        />
      </view>
    </wd-popup>

    <!-- 表单弹窗 -->
    <wd-popup
      v-model="formVisible"
      position="bottom"
      :safe-area-inset-bottom="true"
      class="warehouse-form-popup"
      @close="formVisible = false"
    >
      <view class="popup-container">
        <WarehouseForm
          v-if="formVisible"
          :warehouse="currentWarehouse"
          @submit="handleFormSubmit"
          @cancel="formVisible = false"
        />
      </view>
    </wd-popup>

    <!-- 加载状态 -->
    <wd-loading v-if="loading" />
  </view>
</template>

<style lang="scss" scoped>
/* Apple 设计系统变量 */
:root {
  --apple-blue: #007aff;
  --apple-blue-light: #5ac8fa;
  --apple-blue-dark: #0056cc;
  --apple-gray: #8e8e93;
  --apple-gray-light: #c7c7cc;
  --apple-gray-dark: #48484a;
  --apple-red: #ff3b30;
  --apple-green: #34c759;
  --apple-orange: #ff9500;
  --apple-purple: #af52de;
  --apple-background: #f2f2f7;
  --apple-surface: #ffffff;
  --apple-radius: 12px;
  --apple-radius-small: 8px;
  --apple-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  --apple-shadow-elevated: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.warehouse-page {
  min-height: 100vh;
  background: var(--apple-background);
  padding: 16px;
  padding-top: 8px;
}

.action-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 12px;
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 0.5px solid #c7c7cc;

  .action-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 12px;
    border-radius: 10px;
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    font-weight: 600;
    font-size: 14px;
    border: 1px solid;
    min-height: 36px;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, transparent 100%);
      opacity: 0;
      transition: opacity 0.2s ease;
    }

    &:active::before {
      opacity: 1;
    }

    &.add-btn {
      color: white;
      background: linear-gradient(135deg, #007aff 0%, #5ac8fa 100%);
      border-color: #007aff;
      box-shadow: 0 2px 8px rgba(0, 122, 255, 0.25);

      &:active {
        transform: scale(0.95);
        box-shadow: 0 1px 4px rgba(0, 122, 255, 0.3);
      }

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
        transform: translateY(-1px);
      }
    }

    &.delete-btn {
      color: #ff3b30;
      background: linear-gradient(135deg, rgba(255, 59, 48, 0.1) 0%, rgba(255, 149, 0, 0.1) 100%);
      border-color: rgba(255, 59, 48, 0.2);
      box-shadow: 0 1px 4px rgba(255, 59, 48, 0.1);

      &:active {
        transform: scale(0.95);
        background: linear-gradient(135deg, rgba(255, 59, 48, 0.2) 0%, rgba(255, 149, 0, 0.2) 100%);
        box-shadow: 0 1px 2px rgba(255, 59, 48, 0.2);
      }

      &:hover:not(.disabled) {
        box-shadow: 0 2px 8px rgba(255, 59, 48, 0.15);
        transform: translateY(-1px);
      }

      &.disabled {
        color: #8e8e93;
        background: linear-gradient(
          135deg,
          rgba(142, 142, 147, 0.1) 0%,
          rgba(199, 199, 204, 0.1) 100%
        );
        border-color: rgba(142, 142, 147, 0.2);
        box-shadow: none;
        cursor: not-allowed;

        &:active {
          transform: none;
          box-shadow: none;
        }
      }
    }
  }
}

.warehouse-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.pagination-section {
  background: var(--apple-surface);
  border-radius: var(--apple-radius);
  padding: 16px;
  margin-top: 16px;
  display: flex;
  justify-content: center;
  box-shadow: var(--apple-shadow);
  border: 0.5px solid var(--apple-gray-light);
}

/* 弹窗样式 */
.warehouse-detail-popup,
.warehouse-form-popup {
  .popup-container {
    background: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .warehouse-page {
    background: #1c1c1e;
  }

  .action-section {
    background: #2c2c2e;
    border-color: #3a3a3c;
  }

  .pagination-section {
    background: #2c2c2e;
    border-color: #3a3a3c;
  }

  .warehouse-detail-popup,
  .warehouse-form-popup {
    .popup-container {
      background: #1c1c1e;
    }
  }
}

/* 响应式设计 */
@media screen and (max-width: 750px) {
  .warehouse-page {
    padding: 12px;
  }

  .action-section {
    padding: 10px;
    gap: 6px;

    .action-btn {
      padding: 6px 10px;
      min-height: 32px;
      font-size: 13px;
      gap: 4px;
    }
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .loading-content {
    background: var(--apple-surface);
    border-radius: var(--apple-radius);
    padding: 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    box-shadow: var(--apple-shadow-elevated);

    .loading-text {
      font-size: 14px;
      color: var(--apple-gray);
    }
  }
}
</style>
